package com.mingren.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.mingren.config.CosClientConfig;
import com.mingren.exception.BusinessException;
import com.mingren.exception.ErrorCode;
import com.mingren.manager.CosManager;
import com.mingren.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author 曹宏福
 * @version 1.0
 * 抽象模板类
 */
@Slf4j
public abstract class PictureUploadTemplate {

    @Resource
    protected CosManager cosManager;

    @Resource
    protected CosClientConfig cosClientConfig;

    /**
     * 模板方法->定义上传流程
     *
     * @param inputSource      文件
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
    public UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        // 1、执行校验图片逻辑
        validPicture(inputSource);
        // 2、编辑图片上传地址
        // 2.1 UUDI
        String UUID = RandomUtil.randomString(7);
        // 2.2 获取文件源名称
        String originalFilename = getOriginFilename(inputSource);
        // 3、拼接上传文件的路径
        String uploadFilename = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "_" + UUID + "." + FileUtil.getSuffix(originalFilename);
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
        File file = null;
        //上传文件逻辑
        try {
            /**
             * 这行代码调用了 File 类的静态方法 createTempFile 来创建一个临时文件。
             * filepath：这个参数通常作为临时文件名称的前缀
             * 表示临时文件名称的后缀
             */
            file = File.createTempFile(uploadPath, null);
            /**
             * 3、处理输入源并生成本地临时文件保存在内存中
             */
            processFile(inputSource, file);
            /**
             * 4、上传图片到对象存储
             */
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);

            // 获取图片信息对象、封装返回信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();

            // 获取到图片处理结果
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();

            if (CollUtil.isNotEmpty(objectList)) {
                //如果图片处理结果不为空 如果没有缩略图则缩略图默认等于压缩图
                //获取以图搜图url
                CIObject pngObject = objectList.get(0);
                //获取压缩之后的文件信息
                CIObject compressedCiObject = objectList.get(1);
                //缩略图默认等于压缩图
                CIObject thumbnailCiObject = compressedCiObject;
                // 生成缩略图才获取缩略图
                if (objectList.size() > 2) {
                    thumbnailCiObject = objectList.get(2);
                }
                //返回封装压缩图的返回结果
                //return buildResult(originalFilename, compressedCiObject, thumbnailCiObject, imageInfo);
                return buildResult(originalFilename,pngObject, compressedCiObject, thumbnailCiObject, imageInfo);
            }
            /**
             * 5、封装返回结果
             */
            return buildResult(originalFilename, file, uploadPath, imageInfo);
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            // 清理临时文件
            deleteTempFile(file);
        }
    }

    /**
     * 校验输入源（本地文件或 URL）
     */
    protected abstract void validPicture(Object inputSource);

    /**
     * 获取输入源的原始文件名
     */
    protected abstract String getOriginFilename(Object inputSource);

    /**
     * 处理输入源并生成本地临时文件
     */
    protected abstract void processFile(Object inputSource, File file) throws Exception;

    /**
     * 清理临时文件
     */
    public void deleteTempFile(File TempFile) {
        if (TempFile == null) {
            //如果文件为空直接返回
            return;
        }
        //如果文件不为空 则需要删除暂存的当前文件
        boolean deleteResult = TempFile.delete();
        if (!deleteResult) {
            //如果临时文件删除失败则打出日志失效
            log.error("file delete error, filepath = {}", TempFile.getAbsolutePath());
        }
    }

    /**
     * 封装返回结果
     *
     * @param originalFilename   原始文件名
     * @param compressedCiObject 压缩后的对象
     * @param thumbnailCiObject  缩略图对象
     * @param imageInfo          图片信息
     * @return
     */
    private UploadPictureResult buildResult(String originalFilename, CIObject compressedCiObject, CIObject thumbnailCiObject,
                                            ImageInfo imageInfo) {
        // 计算宽高
        int picWidth = compressedCiObject.getWidth();
        int picHeight = compressedCiObject.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        // 封装返回结果
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        // 设置压缩后的原图地址
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());
        //设置颜色的值
        uploadPictureResult.setPicColor(imageInfo.getAve());
        // 设置缩略图地址
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());
        // 返回可访问的地址
        return uploadPictureResult;
    }
    /**
     * 封装返回结果
     * @param originalFilename   原始文件名
     * @param compressedCiObject 压缩后的对象
     * @param thumbnailCiObject  缩略图对象
     * @param pngObject          以图搜图url
     * @param imageInfo          图片信息
     * @return
     */
    private UploadPictureResult buildResult(String originalFilename, CIObject pngObject,CIObject compressedCiObject, CIObject thumbnailCiObject,
                                            ImageInfo imageInfo) {
        // 计算宽高
        int picWidth = compressedCiObject.getWidth();
        int picHeight = compressedCiObject.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        // 封装返回结果
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        // 设置压缩后的原图地址
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());
        //设置颜色的值
        uploadPictureResult.setPicColor(imageInfo.getAve());
        // 设置缩略图地址
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());
        //设置以图搜图url
        uploadPictureResult.setJpgOrPngUrl(cosClientConfig.getHost() + "/" + pngObject.getKey());
        // 返回可访问的地址
        return uploadPictureResult;
    }
    /**
     * 封装返回结果
     *
     * @param originalFilename 原始文件名
     * @param file             文件
     * @param uploadPath       上传的路径
     * @param imageInfo        对象存储返回的图片信息
     * @return
     */
    private UploadPictureResult buildResult(String originalFilename, File file, String uploadPath, ImageInfo imageInfo) {
        // 计算宽高
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        // 封装返回结果
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        uploadPictureResult.setPicColor(imageInfo.getAve());
        // 返回可访问的地址
        return uploadPictureResult;
    }
}
